#compare 1.1 > 2.3.1.1
#compare 2.6.5.4 > 10.1
source("https://gitee.com/ry2an/my_public_functions_r/raw/master/rep_in_one.R")
library(stringr)


fix_code <- function(num = 0){
  return(paste(rep_in_one("0.", (num - 1)), "0", sep = ""))
}

fill_code <- function(names = c(),sep = "\\."){
  level_vec <- str_count(string = names, pattern = sep) + 1
  max_level <- max(level_vec)
  new_string <- names
  for(i in 1:length(new_string)){
    new_string[i] <- paste(new_string[i], 
                           fix_code(max_level - level_vec[i]),
                           sep = "")
  }
  return(list(new_string, max_level))
}

c1_larger_tf <- function(c1 = "0", c2 = "0", sep = "\\.", sametf = F, silent = T){
  if(silent == F){
    cat("now compare ", c1, "---", c2, " \n", sep = "")
  }
  if(c1 == c2){
    return(sametf)
  }
  if(is.na(str_locate(string = c1, pattern = sep)[1])){
    return(as.numeric(c1) > as.numeric(c2))
  }else{
    curc1 <- as.numeric(substr(c1, start = 1, stop = str_locate(string = c1, pattern = sep)[1]))
    curc2 <- as.numeric(substr(c2, start = 1, stop = str_locate(string = c2, pattern = sep)[1]))
    if(curc1 != curc2){
      return(curc1 > curc2)
    }else{
      c1sp <- substr(c1, start = str_locate(string = c1, pattern = sep)[2] + 1, stop = nchar(c1))
      c2sp <- substr(c2, start = str_locate(string = c2, pattern = sep)[2] + 1, stop = nchar(c2))
      return(c1_larger_tf(c1 = c1sp, c2 = c2sp, sep = sep, silent = silent))
    }
    
  }
}

judge_order <- function(vec = c(), sep = "\\.", desc = F, silent = T){
  ori_order <- 1:length(vec)
  fill_vec <- fill_code(names = vec, sep = sep)[[1]]
  
  if(length(ori_order) == 1){
    return(1)
  }
  
  count_df <- data.frame(ori_order, fill_vec)
  clear_mark <- 0
  while(clear_mark != 1){
    clear_mark = 1
    for(i in 1:(dim(count_df)[1] - 1)){
      if(c1_larger_tf(c1 = count_df$fill_vec[i], 
                      c2 = count_df$fill_vec[i + 1], silent = silent)){
        if(silent == F){
          cat("Order Changed\n")
        }
        clear_mark = 0
        if(i + 2 <= dim(count_df)[1]){
          if(i == 1){
            count_df <- count_df[c((i+1), i, (i+2):dim(count_df)[1]),]
          }else{
            count_df <- count_df[c(1:(i-1), (i+1), i, (i+2):dim(count_df)[1]),]
          }
        }else{
          if(i == 1){
            count_df <- count_df[c((i+1), i),]
          }else{
            count_df <- count_df[c(1:(i-1), (i+1), i),]
          }
        }
      }
    }
  }
  count_df$new_order <- 1:length(vec)
  count_df <- count_df[order(count_df$ori_order),]
  if(desc){
    return((max(count_df$new_order) + 1) - count_df$new_order)
  }else{
    return(count_df$new_order)
  }
}

#### TEST AREA ####
# c("2.6.4",
# "10.5.3.3.1",
# "2.5",
# "4.1.3")[judge_order(vec = c("2.6.4",
#                              "10.5.3.3.1",
#                              "2.5",
#                              "4.1.3"))]
# judge_order(vec = c("2.6.4","10.5.3.3.1","2.5","4.1.3"))
